package com.ruoyi.shop.goods.service.impl;

import java.util.List;
import java.util.stream.Collectors;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Comparator;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.shop.goods.vo.ShopGoodsVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.shop.common.constant.ShopConstants;
import com.ruoyi.shop.common.exception.ShopException;
import com.ruoyi.shop.common.utils.ShopUtils;
import com.ruoyi.shop.goods.domain.ShopGoods;
import com.ruoyi.shop.goods.domain.ShopGoodsAttr;
import com.ruoyi.shop.goods.domain.ShopGoodsSku;
import com.ruoyi.shop.goods.mapper.ShopGoodsAttrMapper;
import com.ruoyi.shop.goods.mapper.ShopGoodsMapper;
import com.ruoyi.shop.goods.mapper.ShopGoodsSkuMapper;
import com.ruoyi.shop.goods.service.IShopGoodsService;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 商品Service业务层处理
 * 
 * @author xuxiang
 * @date 2021-11-22
 */
@Service
public class ShopGoodsServiceImpl implements IShopGoodsService {
	@Autowired
	private ShopGoodsMapper shopGoodsMapper;
	@Autowired
	private ShopGoodsSkuMapper shopGoodsSkuMapper;
	@Autowired
	private ShopGoodsAttrMapper shopGoodsAttrMapper;

	/**
	 * 查询商品
	 * 
	 * @param goodsId 商品主键
	 * @return 商品
	 */
	@Override
	public ShopGoodsVo selectGoodsById(Long goodsId) {
		ShopGoodsVo goodsVo = shopGoodsMapper.selectGoodsById(goodsId);
		// 运费保留2位小数
		goodsVo.setFreight(goodsVo.getFreight().setScale(1, RoundingMode.HALF_UP));
		// 设置规格数据
		goodsVo.setGoodsSkus(shopGoodsSkuMapper.selectListByGoodsId(goodsId));
		// 设置属性数据
		goodsVo.setGoodsAttrs(shopGoodsAttrMapper.selectListByGoodsId(goodsId));
		// 处理图片路径
		String content = goodsVo.getContent().replaceAll(ShopConstants.SHOP_DOMAIN_PREFIX, ShopUtils.getDomain());
		goodsVo.setContent(content);
		return goodsVo;
	}

	/**
	 * 查询商品列表
	 * 
	 * @param shopGoods 商品
	 * @return 商品
	 */
	@Override
	public List<ShopGoodsVo> selectGoodsList(ShopGoods shopGoods) {
		return shopGoodsMapper.selectGoodsList(shopGoods);
	}

	/**
	 * 新增商品
	 * 
	 * @param shopGoods 商品
	 * @return 结果
	 */
	@Transactional
	@Override
	public int insertGoods(ShopGoodsVo goodsVo) {
		ShopGoods goods = goodsVo;
		List<ShopGoodsSku> skuList = goodsVo.getGoodsSkus();
		try {
			goods.setPrice(skuList.stream().min(Comparator.comparing(ShopGoodsSku::getPrice)).get().getPrice());
			goods.setCost(skuList.stream().min(Comparator.comparing(ShopGoodsSku::getCost)).get().getCost());
			goods.setMarketPrice(
					skuList.stream().min(Comparator.comparing(ShopGoodsSku::getMarketPrice)).get().getMarketPrice());
			goods.setStock(skuList.stream().min(Comparator.comparing(ShopGoodsSku::getStock)).get().getStock());
			goods.setCreateTime(DateUtils.getNowDate());
			goods.setUpdateTime(DateUtils.getNowDate());
			// 处理图片路径
			String content = goodsVo.getContent().replaceAll(ShopUtils.getDomain(), ShopConstants.SHOP_DOMAIN_PREFIX);
			goodsVo.setContent(content);
			// 自提或包邮
			if (goodsVo.getFreightType() == 0) {
				goodsVo.setFreightType(0);
				goodsVo.setFreight(BigDecimal.ZERO);
				goodsVo.setFreightId(Long.valueOf(0));
			}
			// 固定运费
			if (goodsVo.getFreightType() == 1) {
				goodsVo.setFreightId(Long.valueOf(0));
			}
			// 增加商品记录
			shopGoodsMapper.insertGoods(goods);
			skuList.forEach(sku -> sku.setGoodsId(goodsVo.getGoodsId()));
			// 增加商品sku记录
			shopGoodsSkuMapper.insertGoodsSkuList(skuList);
			List<ShopGoodsAttr> attrList = new ArrayList<ShopGoodsAttr>();
			if (ShopConstants.SHOP_SPEC_TYPE_SINGLE.equals(goodsVo.getSpecType())) {
				ShopGoodsAttr goodsAttr = new ShopGoodsAttr("默认", "默认");
				goodsAttr.setCreateTime(DateUtils.getNowDate());
				attrList.add(goodsAttr);
			} else {
				attrList = goodsVo.getGoodsAttrs().stream().filter(item -> StringUtils.isNotEmpty(item.getAttrName()))
						.collect(Collectors.toList());
			}
			attrList.forEach(attr -> {
				attr.setGoodsId(goodsVo.getGoodsId());
				attr.setCreateTime(DateUtils.getNowDate());
			});
			// 增加商品属性记录
			shopGoodsAttrMapper.insertGoodsAttrList(attrList);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ShopException("新增商品错误" + e.getMessage());
		}
		return 1;
	}

	/**
	 * 修改商品
	 * 
	 * @param shopGoods 商品
	 * @return 结果
	 */
	@Transactional
	@Override
	public int updateGoods(ShopGoodsVo goodsVo) {
		ShopGoods goods = goodsVo;
		List<ShopGoodsSku> skuList = goodsVo.getGoodsSkus();
		try {
			goods.setPrice(skuList.stream().min(Comparator.comparing(ShopGoodsSku::getPrice)).get().getPrice());
			goods.setCost(skuList.stream().min(Comparator.comparing(ShopGoodsSku::getCost)).get().getCost());
			goods.setMarketPrice(
					skuList.stream().min(Comparator.comparing(ShopGoodsSku::getMarketPrice)).get().getMarketPrice());
			goods.setStock(skuList.stream().min(Comparator.comparing(ShopGoodsSku::getStock)).get().getStock());
			goods.setUpdateTime(DateUtils.getNowDate());
			String content = goodsVo.getContent().replaceAll(ShopUtils.getDomain(), ShopConstants.SHOP_DOMAIN_PREFIX);
			goodsVo.setContent(content);
			// 自提或包邮
			if (goodsVo.getFreightType() == 0) {
				goodsVo.setFreightType(0);
				goodsVo.setFreight(BigDecimal.ZERO);
				goodsVo.setFreightId(Long.valueOf(0));
			}
			// 固定运费
			if (goodsVo.getFreightType() == 1) {
				goodsVo.setFreightId(Long.valueOf(0));
			}

			List<ShopGoodsSku> insertSkuList = new ArrayList<ShopGoodsSku>();// 新增sku集合
			List<ShopGoodsSku> updateSkuList = new ArrayList<ShopGoodsSku>();// 更新sku集合
			for (ShopGoodsSku newSku : skuList) {
				ShopGoodsSku oldSku = shopGoodsSkuMapper.selectByGoodsIdAndSkuName(goodsVo.getGoodsId(),
						newSku.getSkuName());// 原sku记录
				if (StringUtils.isNull(oldSku)) {
					newSku.setGoodsId(goodsVo.getGoodsId());
					insertSkuList.add(newSku);
				} else {
					newSku.setGoodsId(goodsVo.getGoodsId());
					newSku.setSkuId(oldSku.getSkuId());
					updateSkuList.add(newSku);
				}
			}
			// 修改商品主表记录
			shopGoodsMapper.updateGoods(goods);
			// 先清空商品属性集合
			shopGoodsAttrMapper.deleteByGoodsId(goodsVo.getGoodsId());
			List<ShopGoodsAttr> attrList = new ArrayList<ShopGoodsAttr>();
			// 单规格
			if (ShopConstants.SHOP_SPEC_TYPE_SINGLE.equals(goodsVo.getSpecType())) {
				attrList = new ArrayList<ShopGoodsAttr>();
				ShopGoodsAttr goodsAttr = new ShopGoodsAttr("默认", "默认");
				goodsAttr.setCreateTime(DateUtils.getNowDate());
				attrList.add(goodsAttr);
			} else {
				attrList = goodsVo.getGoodsAttrs().stream().filter(item -> StringUtils.isNotEmpty(item.getAttrName()))
						.collect(Collectors.toList());
			}
			attrList.forEach(attr -> {
				attr.setGoodsId(goodsVo.getGoodsId());
				attr.setCreateTime(DateUtils.getNowDate());
			});
			// 再新增商品属性集合
			shopGoodsAttrMapper.insertGoodsAttrList(attrList);
			// 先清空商品sku集合
			shopGoodsSkuMapper.deleteByGoodsId(goodsVo.getGoodsId());
			// 增加商品sku记录
			updateSkuList.forEach(item -> {
				// 原id插入
				shopGoodsSkuMapper.insertGoodsSku(item);
			});
			// 无id插入
			if (insertSkuList.size() > 0) {
				shopGoodsSkuMapper.insertGoodsSkuList(insertSkuList);
			}
		} catch (Exception e) {
			throw new ShopException("编辑商品错误" + e.getMessage());
		}
		return 1;
	}

	/**
	 * 商品状态修改
	 * 
	 * @param goods 商品
	 * @return 结果
	 */
	@Override
	public int changeStatus(ShopGoods goods) {
		return shopGoodsMapper.updateGoods(goods);
	}

	/**
	 * 批量删除商品
	 * 
	 * @param ids 需要删除的商品主键集合
	 * @return 结果
	 */
	@Override
	public int deleteGoodsByIds(String ids) {
		return shopGoodsMapper.deleteGoodsByIds(Convert.toLongArray(ids));
	}

	/**
	 * 查询商品销量排行榜
	 * 
	 * @param top
	 * @return
	 */
	@Override
	public List<ShopGoods> queryTopList(Integer top) {
		return shopGoodsMapper.queryTopList(top);
	}

}
